import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import http from '@/utils/http'
import type { ApiResponse } from '@/types/api'

// 科室接口
export interface DepartmentVO {
  id: number
  name: string
}

// 职称接口
export interface TitleVO {
  id: number
  title: string
}

export const useDoctorDataStore = defineStore(
  'doctorData',
  () => {
    // 科室列表
    const departments = ref<DepartmentVO[]>([])
    // 职称列表
    const titles = ref<TitleVO[]>([])
    // 加载状态
    const loading = ref({
      departments: false,
      titles: false
    })
    // 是否已初始化
    const initialized = ref({
      departments: false,
      titles: false
    })

    // 获取科室列表
    async function fetchDepartments() {
      if (loading.value.departments) return

      // 如果已经有数据，直接返回
      if (initialized.value.departments && departments.value.length > 0) {
        return departments.value
      }

      loading.value.departments = true
      try {
        const res = await http<ApiResponse<DepartmentVO[]>>({
          url: '/user/appointment/doctorDepartment',
          method: 'GET'
        })

        if (res.status === 200 && res.data) {
          departments.value = res.data.data || []
          initialized.value.departments = true
        } else {
          console.error('获取科室列表失败:', res.data?.message || '未知错误')
        }
        return departments.value
      } catch (error) {
        console.error('获取科室列表异常:', error)
        return []
      } finally {
        loading.value.departments = false
      }
    }

    // 获取职称列表
    async function fetchTitles() {
      if (loading.value.titles) return

      // 如果已经有数据，直接返回
      if (initialized.value.titles && titles.value.length > 0) {
        return titles.value
      }

      loading.value.titles = true
      try {
        const res = await http<ApiResponse<TitleVO[]>>({
          url: '/user/appointment/doctorTitle',
          method: 'GET'
        })

        if (res.status === 200 && res.data) {
          titles.value = res.data.data || []
          initialized.value.titles = true
        } else {
          console.error('获取职称列表失败:', res.data?.message || '未知错误')
        }
        return titles.value
      } catch (error) {
        console.error('获取职称列表异常:', error)
        return []
      } finally {
        loading.value.titles = false
      }
    }

    // 获取科室名称列表（仅名称）
    const departmentNames = computed(() => {
      return departments.value.map(dept => dept.name)
    })

    // 获取职称名称列表（仅名称）
    const titleNames = computed(() => {
      return titles.value.map(title => title.title)
    })

    return {
      departments,
      titles,
      loading,
      initialized,
      fetchDepartments,
      fetchTitles,
      departmentNames,
      titleNames
    }
  },
  {
    persist: true // 持久化存储
  }
)
